#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main()
{
	int pipefd[2] = {};
	// 打开无名管道
	if(pipe(pipefd))
	{
		perror("pipe");
		return -1;
	}
	
	// 创建进程
	pid_t id = fork();

	if(id)
	{// 父进程写入
		usleep(100);//延时
		//关闭读
		close(pipefd[0]);
		char buf[1024] = {};
		printf("我是父进程%u,我要和我的子进程%u开始通信\n",getpid(),id);
		for(;;)
		{
			usleep(100);
			printf(">");
			gets(buf);
			write(pipefd[1],buf,strlen(buf)+1);
			if(0 == strcmp("quit",buf))
			{
				printf("父进程通信结束!");
				close(pipefd[1]);
				return 0;
			}
		}
	}
	else
	{// 子进程读
		// 关闭写
		close(pipefd[1]);
		char buf[1024] = {};
		printf("我是子进程%u,我要和我的父进程%u通信了\n",getpid(),getppid());
		for(;;)
		{
			read(pipefd[0],buf,sizeof(buf));
			printf("read:%s\n",buf);
			if(0 == strcmp("quit",buf))
			{
				printf("子进程通信完成!\n");
				close(pipefd[0]);
				return 0;
			}
		}
	}
}
